﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using Infrastructure.DAL.SeedWork.Extension;
using Infrastructure.Domain.SeedWork;
using Infrastructure.Repository.EntityFramework.UnitOfWork;

namespace Infrastructure.Repository.EntityFramework.Extension
{
    public class BatchInsert : IBatchRepository
    {
        private readonly BaseEFUnitOfWork _dbContext;

        public BatchInsert(BaseEFUnitOfWork dbContext)
        {
            _dbContext = dbContext;
        }

        public void BatchInsertEnties<TEntity>(List<TEntity> entities) where TEntity : class, IDomain
        {
            if (_dbContext.BatchEntityConfigs.ContainsKey(typeof (TEntity).FullName))
            {
                throw new Exception(string.Format("the DbContext not has config of {0}", typeof (TEntity).FullName));
            }
            using (var connection = new SqlConnection(_dbContext.Database.Connection.ConnectionString))
            {
                SqlTransaction transaction = null;
                connection.Open();
                try
                {
                    transaction = connection.BeginTransaction();
                    using (var sqlBulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
                    {
                        //sqlBulkCopy.BatchSize = entities.Count;
                        //sqlBulkCopy.DestinationTableName = _dbContext.BatchEntityConfigs[typeof(TEntity).FullName].TableName;
                        //_dbContext.BatchEntityConfigs[typeof(TEntity).FullName]
                        //          .ColumnMappings
                        //          .ForEach(item => sqlBulkCopy.ColumnMappings.Add(item.Key, item.Value));
                        //EntityHelper.GetPropertiesAttributesDict<TEntity,BatchInsertMappingAttribute>()
                        //            .ToList().ForEach(item => sqlBulkCopy.ColumnMappings.Add(item.Key, item.Value.MappingColumnName));
                        //sqlBulkCopy.WriteToServer(entities.ToDataTable());
                    }
                    transaction.Commit();
                }
                catch
                {
                    if (transaction != null)
                    {
                        transaction.Rollback();
                    }
                    throw;
                }
            }
        }
    }
}